package com.jxd.dianping.controller.admin;

import com.jxd.dianping.common.AdminPermission;
import com.jxd.dianping.common.BusinessException;
import com.jxd.dianping.common.CommonRes;
import com.jxd.dianping.common.EmBusinessError;
import com.jxd.dianping.service.CategoryService;
import com.jxd.dianping.service.SellerService;
import com.jxd.dianping.service.ShopService;
import com.jxd.dianping.service.UserService;
import com.mysql.jdbc.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Controller
public class AdminController {

    @Value("${admin.email}")
    private String email;
    @Value("${admin.encryptPassword}")
    private String encryptPassword;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserService userService;
    @Autowired
    private SellerService sellerService;
    @Autowired
    private ShopService shopService;
    @Autowired
    private CategoryService categoryService;

    public static String CURRENT_ADMIN_SESSION="currentAdminSession";

    @RequestMapping("/admin/admin/index")
    @AdminPermission
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView("/admin/admin/index.html");
        modelAndView.addObject("CONTROLLER_NAME","admin");
        modelAndView.addObject("ACTION_NAME", "index");
        modelAndView.addObject("userCount", userService.countAllUser());
        modelAndView.addObject("sellerCount", sellerService.countAllSeller());
        modelAndView.addObject("shopCount", shopService.countAllShop());
        modelAndView.addObject("categoryCount", categoryService.countAllCategory());
        return modelAndView;
    }

    @RequestMapping("/admin/admin/loginPage")
    public ModelAndView loginPage() {
        return new ModelAndView("admin/admin/login.html");
    }

    @RequestMapping(value = "/admin/admin/login", method=RequestMethod.POST)
    public String login(@RequestParam(name = "email") String email,
                              @RequestParam(name = "password") String password) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        if (StringUtils.isEmptyOrWhitespaceOnly(email) || StringUtils.isEmptyOrWhitespaceOnly(password)) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,"用户名和密码不得为空");
        }
        if (email.equals(this.email) && encodeByMd5(password).equals(this.encryptPassword)) {
            request.getSession().setAttribute(CURRENT_ADMIN_SESSION, email);
            return "redirect:/admin/admin/index.html";
        } else {
            throw new BusinessException(EmBusinessError.LOGIN_ERROR, "用户名或密码错误");
        }
    }

    private String encodeByMd5(String rawPassword) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encode(messageDigest.digest(rawPassword.getBytes(StandardCharsets.UTF_8)));
    }

    /**
     * 测试AdminPermission在rest api中的使用
     * @return
     */
    @RequestMapping("/test")
    @AdminPermission(produceType = "application/json")
    @ResponseBody
    public CommonRes test() {
        return CommonRes.create(null);
    }
}
